import {Injectable} from '@angular/core';
import {AlertMessage} from '../entity/alert-message';
import {BehaviorSubject} from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class MessageService {
    /**
     * 站内信息列表
     */
    private _messages: AlertMessage[] = [];

    private messagesBehavior = new BehaviorSubject([]);

    messageProvider = this.messagesBehavior.asObservable();

    constructor() {
    }

    /**
     * 推送一条消息
     * @param {AlertMessage} message
     */
    add(message: AlertMessage): void {
        const hasNew = this.addItem(message);
        if (hasNew) {
            this.messagesBehavior.next(this._messages);
        }
    }

    /**
     * 推送多条信息
     * @param {AlertMessage[]} messages
     */
    addAll(messages: AlertMessage[]): void {
        let hasNew = false;
        messages.forEach((message: AlertMessage) => {
            const success = this.addItem(message);
            if (success) {
                hasNew = true;
            }
        });
        if (hasNew) {
            this.messagesBehavior.next(this._messages);
        }
    }

    /**
     * 删除一条消息
     * @param {AlertMessage} message
     */
    remove(message: AlertMessage): void {
        if (message.interval) {
            clearInterval(message.interval);
        }
        this._messages = this._messages.filter(item => message !== item);
        this.messagesBehavior.next(this._messages);
    }

    removeAll(): void {
        this._messages = [];
        this.messagesBehavior.next(this._messages);
    }

    /**
     * 推送一条消息
     * @param {AlertMessage} message
     * @returns {boolean} 是否添加成功
     */
    private addItem(message: AlertMessage): boolean {
        let exists = false;
        this._messages.forEach(item => {
            if (item.id === message.id) {
                exists = true;
            }
        });
        if (!exists) {
            this._messages.push(message);
            // 添加计数器
            if (message.time) {
                message.interval = setInterval(() => {
                    --message.time;
                    if (message.time <= 0) {
                        this.remove(message);
                    }
                }, 1000);
            }
            return true;
        }
        return false;
    }

    removeById(messageId: string) {
        this._messages.forEach(message => {
            if (message.id === messageId) {
                this.remove(message);
                return;
            }
        });
    }
}
